import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/model/shop/pdd_cate_model.dart';
import 'package:flutter_yres/model/shop/pdd_list.model.dart';
import 'package:flutter_yres/pages/shop/pdd_detail_page.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../tool/md5_sign.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';

class PddSubPage extends StatefulWidget {
  String pdd_id;
   String pdd_cat_id;
  PddSubPage({Key key, this.pdd_id, this.pdd_cat_id}) : super(key: key);

  @override
  _PddSubPageState createState() => _PddSubPageState(pdd_id);
}

class _PddSubPageState extends State<PddSubPage> {
  String pdd_id;
  _PddSubPageState(this.pdd_id);
  EasyRefreshController _controller = new EasyRefreshController();
  List<PddCateModelData> subs = []; //拼多多子级分类数组
  int page = 1;
  var search = '';
  List<PddListModelData> shopData = []; //拼多多商品

  double _listHeight = ScreenUtil.getInstance().setHeight(260); //单个列表高度

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: _buildSub(),
    );
  }

  //其他类别主页内容
  Widget _buildSub() {
    return Container(
      child: new EasyRefresh(
        //刷新  加载组件
        enableControlFinishRefresh: true,
              enableControlFinishLoad: true,
              controller: _controller,
              header: MaterialHeader(),
              footer: MaterialFooter(),
        child: CustomScrollView(slivers: <Widget>[
          SliverGrid(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 5,
              mainAxisSpacing: 8.0,
              crossAxisSpacing: 10.0,
              childAspectRatio: 0.85, //子控件宽高比
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return _itemBuilder(context, subs[index]);
              },
              childCount: subs.length,
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
                height: ScreenUtil.getInstance().setHeight(60),
                child: Column(
                  children: <Widget>[_buildPopHeader()],
                )),
          ),
          SliverFixedExtentList(
              delegate: SliverChildBuilderDelegate(_buildListItem,
                  childCount: shopData.length),
              itemExtent: _listHeight),
        ]),
        onRefresh: () async {
          page = 1;
          getPDDShopList();
        },
        onLoad: () async {
          page++;
          getPDDShopList();
        },
      ),
    );
  }

  Widget _itemBuilder(BuildContext context, item) {
    return InkWell(
      onTap: () {
        print(item.name);
        setState(() {
          page = 1;
          search = item.name;
          getPDDShopList();
        });
      },
      child: Column(
        children: <Widget>[
          Container(
            height: ScreenUtil.getInstance().setWidth(20),
          ),
           item.icon==null||item.icon==''?Image.asset(
              'images/logo.png',
              fit: BoxFit.fill,
              width: ScreenUtil.getInstance().setWidth(85),
              height: ScreenUtil.getInstance().setWidth(85),
            ):
          CachedNetworkImage(
            width: ScreenUtil.getInstance().setWidth(85),
            height: ScreenUtil.getInstance().setWidth(85),
            fit: BoxFit.fill,
            imageUrl: Api.BaseUrl + item.icon,
            placeholder: (context, url) => Image.asset(
              'images/logo.png',
              fit: BoxFit.fill,
              width: ScreenUtil.getInstance().setWidth(85),
              height: ScreenUtil.getInstance().setWidth(85),
            ),
            errorWidget: (context, url, error) => Image.asset(
              'images/logo.png',
              fit: BoxFit.fill,
              width: ScreenUtil.getInstance().setWidth(85),
              height: ScreenUtil.getInstance().setWidth(85),
            ),
          ),
          Text(item.name,
              style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(24)), maxLines: 1, overflow: TextOverflow.ellipsis,),
        ],
      ),
    );
  }

//条件筛选头部
  _buildPopHeader() {
    return Container(
      height: ScreenUtil.getInstance().setHeight(60),
      width: ScreenUtil.getInstance().setWidth(750),
      child: Row(
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "综合",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "销量",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "价格",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "佣金",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
        ],
      ),
    );
  }

  Widget _buildListItem(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {
          //处理点击事件
          PddListModelData model = shopData[index];
          // var gasIds=model.gasid;
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) => PddShopDetailPage(
                      pddmodel: model) //打开第二个页面，并传值，传递值的名称是model
                  ));
        },
        child: Container(
            margin: EdgeInsets.fromLTRB(0, ScreenUtil.getInstance().setHeight(15), 0, 0),
            child: Column(
              children: <Widget>[
                Row(children: <Widget>[
                  _leftImage(index),
                  Expanded(
                    child: _rightColumn(index),
                  )
                ], crossAxisAlignment: CrossAxisAlignment.start),
                Divider(
                  height: 1,
                )
              ],
            )));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(l) ?? 0,
            ScreenUtil.getInstance().setHeight(t) ?? 0,
            ScreenUtil.getInstance().setWidth(r) ?? 0,
            ScreenUtil.getInstance().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage(int index) {
    PddListModelData model = shopData[index];
    //左图
    var image = 
    CachedNetworkImage(
            width: ScreenUtil.getInstance().setHeight(180),
        height: ScreenUtil.getInstance().setHeight(180),
        fit: BoxFit.fill,
            imageUrl: model.goods_thumbnail_url,
            placeholder: (context, url) => Image.asset(
              'images/pic_default.png',
              width: ScreenUtil.getInstance().setHeight(180),
        height: ScreenUtil.getInstance().setHeight(180),
        fit: BoxFit.fill,
            ),
            errorWidget: (context, url, error) => Image.asset(
              'images/pic_default.png',
             width: ScreenUtil.getInstance().setHeight(180),
        height: ScreenUtil.getInstance().setHeight(180),
        fit: BoxFit.fill,
            ),
          );
    return _pd(image, l: 20, t: 0, r: 5, b: 40);
  }

  Widget _rightColumn(int index) {
    PddListModelData model = shopData[index];
    //右内容
    var title = Text(
      model.goods_name,
      style: TextStyle(color: Colors.black, fontSize: ScreenUtil.getInstance().setSp(26)),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    var price = RichText(
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(24))),
        TextSpan(
            text: (model.min_group_price / 100 - model.coupon_discount / 100)
                .toStringAsFixed(2),
            style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(27))),
        TextSpan(
          text: (model.min_normal_price / 100).toStringAsFixed(2),
          style: TextStyle(
              fontSize:  ScreenUtil.getInstance().setSp(22),
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var volume = Container(
      child: Text('销量'+model.sales_tip, style: TextStyle(color: Colors.grey,fontSize: ScreenUtil.getInstance().setSp(24))),
    );
    var quanHeader = Container(
      width: ScreenUtil.getInstance().setWidth(40),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_header.png"),
          fit: BoxFit.cover,
        ),
      ),
    );
    var quan = Container(
      width: ScreenUtil.getInstance().setWidth(70),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_footer.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: Center(
          child: Text(
        (model.coupon_discount / 100).toString() + '元',
        style: TextStyle(color: Colors.white, fontSize: ScreenUtil.getInstance().setSp(24)),
      )),
    );
    var yongjin = Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20), 0, ScreenUtil.getInstance().setWidth(20), 0),
      height: ScreenUtil.getInstance().setWidth(34),
      color: Color.fromRGBO(250, 226, 226, 1),
      child: Center(
          child: Text(
              '预估赚¥' +
                  (((model.min_group_price - model.coupon_discount) *
                              (model.promotion_rate / 1000)) /
                          100)
                      .toStringAsFixed(2),
              style: TextStyle(color: Colors.red, fontSize: ScreenUtil.getInstance().setSp(24)))),
    );
    return new Column(
      children: <Widget>[
        _pd(title, l: 10, t: 0, r: 10, b: 8),
        _pd(volume, l: 10, t: 0, r: 10, b: 8),
        _pd(price, l: 10, t: 0, r: 10, b: 8),
        Container(
          margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
          child: Row(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Row(
                  children: <Widget>[quanHeader, quan],
                ),
              ),
              Expanded(flex: 2, child: yongjin)
            ],
          ),
        )
        // Row(
        //   children: <Widget>[_pd(price, l: 10, t: 0, r: 10, b: 8), distance],
        // ),
        // _pd(address, l: 10, t: 0, r: 10, b: 8)
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  @override
  void initState() {
    getPDDSubCatList(this.pdd_id);
    super.initState();
  }

/*拼多多子级列表*/
  getPDDSubCatList(String pdd_id) async {
    FormData data = new FormData.fromMap({'pid': widget.pdd_cat_id});
    Response<String> response =
        await HttpUtil().post(Api.GetPddSubListByParentUrl, data: data);
    Map userMap = json.decode(response.data);
    print('=====自己=======');
    print(userMap);
    PddCateModelEntity itemEntity = new PddCateModelEntity.fromJson(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          subs.clear();
          subs = itemEntity.data;
          if (subs.length > 0) {
            search = subs[0].name;
            getPDDShopList();
          }
        });
      }
    }
  }

  getPDDShopList() async {
    Map map = new Map();
    var timestamp = new DateTime.now().millisecondsSinceEpoch;
    map['type'] = 'pdd.ddk.goods.search';
    // map["sort_type"] = '';
    map["page"] = page;
    map["page_size"] = "10";
    map["cat_id"] = widget.pdd_id;
    map['timestamp'] = "$timestamp";
    map["client_id"]='9cdd5d9fb8ee4d1b94a5f81d005a7922';
    map["data_type"] = "JSON";
    map["version"]="V1";
    print(map);
    String key = '9a103e4e2cfc3b1ea51df0be47fb6e55e8497169';
    List<String> allKeys = [];
    map.forEach((key, value) {
      if (!(value is MultipartFile)) {
        allKeys.add(key.toString() + value.toString());
      }
    });
    allKeys.sort((obj1, obj2) {
      return obj1.compareTo(obj2);
    });
    String pairsString = allKeys.join("");
    print(pairsString);
    String sign = key + pairsString + key;
    String signString = generateMd5(sign).toUpperCase();
    map['sign'] = signString;

    // FormData data = new FormData.fromMap({'page': page, 'keyword': search});
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response = await HttpUtil()
        .post("http://gw-api.pinduoduo.com/api/router?", data: data);
    Map userMap = json.decode(response.data);
    PddListModelEntity itemEntity = new PddListModelEntity.fromJson(userMap);
    print(userMap);
    // if (itemEntity.code == 0) {
      if (mounted) {
        setState(() {
          if (page == 1) {
            shopData.clear();
            shopData = itemEntity.data;
            _controller.finishRefresh();
          } else {
            shopData.addAll(itemEntity.data);
            _controller.finishLoad();
          }
        });
      }
    // }
  }
}
